<template>
  <div class="pay-result-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <div class="spinner"></div>
      <p>正在查询支付结果，请稍候...</p>
    </div>

    <!-- 支付成功状态 -->
    <div v-else-if="payStatus === 'success'" class="result-section success">
      <div class="icon-wrapper success-icon">
        <svg viewBox="0 0 1024 1024" width="80" height="80">
          <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m193.5 301.7l-210.6 292a31.8 31.8 0 0 1-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3h46.9c6.5 0 10.3 7.4 6.5 12.7z" fill="#52c41a"></path>
        </svg>
      </div>
      <h2>支付成功</h2>
      <div class="order-info">
        <p>订单号：{{ orderNo }}</p>
        <p v-if="amount">金额：¥{{ amount }}</p>
        <p v-if="patientName">患者：{{ patientName }}</p>
      </div>
      <div class="action-buttons">
        <button class="primary-button" @click="goToOrders">查看订单</button>
        <button class="secondary-button" @click="goToHome">返回首页</button>
      </div>
    </div>

    <!-- 支付失败状态 -->
    <div v-else-if="payStatus === 'fail'" class="result-section fail">
      <div class="icon-wrapper fail-icon">
        <svg viewBox="0 0 1024 1024" width="80" height="80">
          <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m165.4 618.2l-66-0.3L512 563.4l-99.3 118.4-66.1 0.3c-4.4 0-8-3.5-8-8 0-1.9 0.7-3.7 1.9-5.2l130.1-155L340.5 359c-1.2-1.5-1.9-3.3-1.9-5.2 0-4.4 3.6-8 8-8l66.1 0.3L512 464.6l99.3-118.4 66-0.3c4.4 0 8 3.5 8 8 0 1.9-0.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z" fill="#ff4d4f"></path>
        </svg>
      </div>
      <h2>支付失败</h2>
      <p class="error-message">{{ errorMessage || '支付过程中发生错误，请稍后重试' }}</p>
      <div class="action-buttons">
        <button class="primary-button" @click="retryPayment">重新支付</button>
        <button class="secondary-button" @click="goToHome">返回首页</button>
      </div>
    </div>

    <!-- 未知状态 -->
    <div v-else class="result-section unknown">
      <div class="icon-wrapper unknown-icon">
        <svg viewBox="0 0 1024 1024" width="80" height="80">
          <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m0 708c-22.1 0-40-17.9-40-40s17.9-40 40-40 40 17.9 40 40-17.9 40-40 40z m62.9-219.5c-18.5 7.1-30.9 25.1-30.9 44.8V620c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-21.5c0-23.1 6.7-45.9 19.9-64.9 12.9-18.6 30.9-32.8 52.1-40.9 34-13.1 56-41.6 56-72.7 0-44.1-43.1-80-96-80s-96 35.9-96 80v7.6c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V420c0-39.3 17.2-76 48.4-103.3C430.4 290.4 470 276 512 276s81.6 14.5 111.6 40.7C654.8 344 672 380.7 672 420c0 57.8-38.1 109.8-97.1 132.5z" fill="#faad14"></path>
        </svg>
      </div>
      <h2>支付状态未知</h2>
      <p>我们无法确认您的支付状态，请稍后查看订单</p>
      <div class="action-buttons">
        <button class="primary-button" @click="checkOrderStatus">查询订单状态</button>
        <button class="secondary-button" @click="goToHome">返回首页</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

// 状态变量
const loading = ref(true)
const payStatus = ref('unknown')
const orderNo = ref('')
const amount = ref('')
const patientName = ref('')
const errorMessage = ref('')

// 从URL获取参数
onMounted(async () => {
  try {
    // 从URL中获取支付宝返回的参数
    const { status, orderNo: urlOrderNo } = route.query
    
    if (urlOrderNo) {
      orderNo.value = urlOrderNo
      
      // 如果URL中已有状态参数，先使用它
      if (status === 'success' || status === 'fail' || status === 'error') {
        payStatus.value = status === 'error' ? 'fail' : status
        // 即使有状态还是需要查询详细信息
        await getPaymentDetails(urlOrderNo)
      } else {
        // 否则调用后端接口查询真实支付状态
        await checkPaymentStatus(urlOrderNo)
      }
    } else {
      // 尝试从URL中获取支付宝标准参数
      const outTradeNo = route.query.out_trade_no
      
      if (outTradeNo) {
        orderNo.value = outTradeNo
        // 调用后端接口确认支付状态
        await checkPaymentStatus(outTradeNo)
      } else {
        // 无法获取订单号，显示未知状态
        payStatus.value = 'unknown'
        loading.value = false
      }
    }
  } catch (error) {
    console.error('处理支付回调出错:', error)
    payStatus.value = 'fail'
    errorMessage.value = '查询支付状态时出错'
    loading.value = false
  }
})

// 查询支付状态
async function checkPaymentStatus(orderNum) {
  try {
    const response = await axios.get(`/api/PayconfigController/CheckPayStatus?orderNo=${orderNum}`)
    if (response.data.success) {
      // 根据后端返回的状态设置页面状态
      const status = response.data.status
      if (status === 'success' || status === 'processed') {
        payStatus.value = 'success'
        // 获取订单详细信息
        await getPaymentDetails(orderNum)
      } else if (status === 'fail') {
        payStatus.value = 'fail'
        errorMessage.value = '支付失败'
      } else if (status === 'pending') {
        // 如果是处理中，查询支付宝接口确认最终状态
        await queryFromAlipay(orderNum)
      } else {
        // 查询订单详情，获取更多信息
        await queryFromAlipay(orderNum)
      }
    } else {
      payStatus.value = 'unknown'
    }
  } catch (error) {
    console.error('查询支付状态出错:', error)
    payStatus.value = 'unknown'
  } finally {
    loading.value = false
  }
}

// 获取支付详情
async function getPaymentDetails(orderNum) {
  try {
    const response = await axios.get(`/api/PayConfirmController/GetPayStatus?orderNo=${orderNum}`)
    if (response.data.success && response.data.data) {
      const payData = response.data.data
      if (payData.payStatus === 1) {
        payStatus.value = 'success'
      }
      amount.value = payData.amount
      patientName.value = payData.patientName
    }
  } catch (error) {
    console.error('获取支付详情出错:', error)
  } finally {
    loading.value = false
  }
}

// 从支付宝查询订单状态
async function queryFromAlipay(orderNum) {
  try {
    const response = await axios.get(`/api/PayconfigController/QueryOrder?orderNo=${orderNum}`)
    if (response.data.success) {
      const orderData = JSON.parse(response.data.data)
      if (orderData.alipay_trade_query_response) {
        const tradeInfo = orderData.alipay_trade_query_response
        
        if (tradeInfo.trade_status === 'TRADE_SUCCESS' || tradeInfo.trade_status === 'TRADE_FINISHED') {
          payStatus.value = 'success'
          amount.value = tradeInfo.total_amount
          
          // 支付成功，调用更新接口
          await updatePaymentStatus(orderNum, 1)
        } else if (tradeInfo.trade_status === 'WAIT_BUYER_PAY') {
          payStatus.value = 'unknown'
        } else {
          payStatus.value = 'fail'
          errorMessage.value = tradeInfo.sub_msg || '支付未完成'
        }
      }
    } else {
      payStatus.value = 'unknown'
    }
  } catch (error) {
    console.error('查询支付宝订单出错:', error)
    payStatus.value = 'unknown'
  } finally {
    loading.value = false
  }
}

// 更新支付状态
async function updatePaymentStatus(orderNum, status) {
  try {
    await axios.post('/api/PayConfirmController/UpdatePayStatus', {
      orderNo: orderNum,
      payStatus: status,
      payPlatform: 1 // 支付宝
    })
    console.log('支付状态已更新')
  } catch (error) {
    console.error('更新支付状态出错:', error)
  }
}

// 页面导航函数
function goToOrders() {
  router.push('/orders')
}

function goToHome() {
  router.push('/')
}

function retryPayment() {
  router.push('/payment')
}

function checkOrderStatus() {
  if (orderNo.value) {
    loading.value = true
    checkPaymentStatus(orderNo.value)
  }
}
</script>

<style scoped>
.pay-result-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.loading-section {
  text-align: center;
  padding: 40px 0;
}

.spinner {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #1890ff;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.result-section {
  text-align: center;
  padding: 30px 20px;
}

.icon-wrapper {
  margin-bottom: 20px;
}

.success-icon path {
  fill: #52c41a;
}

.fail-icon path {
  fill: #ff4d4f;
}

.unknown-icon path {
  fill: #faad14;
}

h2 {
  font-size: 24px;
  margin-bottom: 20px;
}

.order-info {
  margin-bottom: 30px;
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  text-align: left;
}

.error-message {
  color: #ff4d4f;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
}

button {
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  border: none;
  transition: all 0.3s;
}

.primary-button {
  background-color: #1890ff;
  color: white;
}

.primary-button:hover {
  background-color: #40a9ff;
}

.secondary-button {
  background-color: #f0f0f0;
  color: #000;
}

.secondary-button:hover {
  background-color: #d9d9d9;
}
</style> 